package com.ws.server.NettyServer;

import com.alibaba.fastjson.JSON;
import com.ws.server.domain.SendMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TextWebSocketFrame是netty用于处理websocket发来的文本对象
 */

public class NettyHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    //所有正在连接的channel都会存在这里面，所以也可以间接代表在线的客户端
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    public List<Map<String, ChannelHandlerContext>> channelList = new ArrayList<Map<String, ChannelHandlerContext>>();
    //在线人数
    public static int online;

    //读取客户端传来的数据
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        System.out.println("接收到用户：" + channelHandlerContext.name() + " 的消息：" + textWebSocketFrame.text());
        SendMessage(channelHandlerContext, new SendMessage("服务端接收到你的消息！！"));
    }


    //客户端建立连接
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channelGroup.add(ctx.channel());
        online = channelGroup.size();
        String name = ctx.channel().id().asLongText();
        System.out.println(name);
        Map<String, ChannelHandlerContext> map = new HashMap<String, ChannelHandlerContext>();
        map.put(name, ctx);
        channelList.add(map);
        System.out.println(ctx.channel().remoteAddress() + "上线了!");
    }

    //关闭连接
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channelGroup.remove(ctx.channel());
        online = channelGroup.size();
        System.out.println(ctx.channel().remoteAddress() + "断开连接");
    }

    //出现异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    //给某个人发送消息
    private void SendMessage(ChannelHandlerContext ctx, SendMessage msg) {
        ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));
    }

    //给每个人发送消息,除发消息人外
    private void SendAllMessages(ChannelHandlerContext ctx, SendMessage msg) {
        for (Channel channel : channelGroup) {
            if (!channel.id().asLongText().equals(ctx.channel().id().asLongText())) {
                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));
            }
        }
    }
}
